#include "stdafx.h"
#include "PPProjTreeReadWriteHelper.h"
#include "LBProjPlanStream\LBProjPlanDataBase.h"

namespace LBPROJ
{
    CPPProjTreeReadWriteHelper::CPPProjTreeReadWriteHelper(CProjectTree* pProjTree)
        : m_pProjTree(pProjTree)
    {
    }


    CPPProjTreeReadWriteHelper::~CPPProjTreeReadWriteHelper()
    {
    }

    bool CPPProjTreeReadWriteHelper::Open(LBPROJSTREAM::IProjPlanStreamDatabase * pDb)
    {
        ReadProjectPlan(pDb);
        return true;
    }

    bool CPPProjTreeReadWriteHelper::Write(LBPROJSTREAM::IProjPlanStreamDatabase * pDb)
    {
        WriteProjectPlan(pDb);
        return true;
    }

    bool CPPProjTreeReadWriteHelper::ReadProjectPlan(LBPROJSTREAM::IProjPlanStreamDatabase * pDb)
    {
        std::list<IProjectTreeNode::Data> lstData;
        if (pDb->ReadProjectPlan(lstData))
            m_pProjTree->GetRoot()->DelAllItem();
        else
            return false;

        for (const auto& data : lstData)
        {
            CRefPtr<IPPContext> pContext = CreateContext();
            pContext->SetID(data.contextId);
            pContext->Open(pDb);

            CRefPtr<IProjectTreeNode> pNode = CreateProjectTreeNode(pContext);
            pNode->SetID(data.id);
            pNode->SetName(data.name);
            CRefPtr<IProjectTreeNode> pParent = m_pProjTree->FindNodeByID(data.parentId);
            if (pParent == nullptr)
                m_pProjTree->GetRoot()->AddItem(pNode);
            else
                pParent->AddItem(pNode);

        }
        return true;
    }

    bool CPPProjTreeReadWriteHelper::WriteProjectPlan(LBPROJSTREAM::IProjPlanStreamDatabase * pDb)
    {
        std::list<IProjectTreeNode::Data> lstData;
        pDb->DelTask();
        pDb->DelPreTask();
        pDb->DeleteProjectPlan();
        int num = 1;
        CRefPtr<IProjectTreeNode> pNode;
        while ((pNode = m_pProjTree->FindNodeBySequence(num)) != nullptr)
        {
            IProjectTreeNode::Data nodeData;
            pNode->Store(nodeData);
            lstData.push_back(nodeData);

            pNode->GetContext()->Write(pDb);

            num++;
        }
        pDb->WriteProjectPlan(lstData);
        return true;
    }
}
